package cn.jiedh.app.meiweidk.web;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.smtt.sdk.WebView;
import cn.jiedh.app.meiweidk.R;
import cn.jiedh.app.meiweidk.Utils.event.EventUtils;
import cn.jiedh.app.meiweidk.Utils.event.Observers;
import cn.jiedh.app.meiweidk.Utils.tool.T;
import cn.jiedh.app.meiweidk.base.BaseActivity;
import cn.jiedh.app.meiweidk.runtimepermissions.PermissionHelper;
import cn.jiedh.app.meiweidk.web.webhandle.ShareBean;

/**
 * @name：
 * @author： liuyun
 * @phone： 15723310658
 * @createTime： 2017/7/21
 * @modifyTime： 2017/7/21
 * @explain：说明
 */


public class WebActivity extends BaseActivity implements WebErrorView.WebErrorViewClickListener ,Observers {
    private static final int PERMISSION_SHARE=8;//分享请求权限的code

    public static final String EXTRA_TITLE = "extra.title";
    public static final String EXTRA_URL = "extra.url";
    public static final String EXTRA_CACHE_MODE = "extra.cache_mode";
    public static final String EXTRA_WEB_TITLE = "extra.web_title";
    public static final String EXTRA_SHARE_DATA="extra.share_data";

    String CUSTOM = "custom_scheme";

    public static final String TAG = "BaseWebViewFragment";

    public static final String TELEPHONY = "tel:";
    public static final String HTTP = "http:";
    public static final String HTTPS = "https:";
    public static final String NATIVE = "mxk" + ":";

    protected CommonWebView mWebView;
    protected WebErrorView mErrorView;
    protected AutoStepProgressBar mProgressBar;
    protected FrameLayout mRootView;

    protected boolean mIsWebViewAvailable;
    protected boolean mDestroyWebView = true;

    protected String mOriginUrl;
    private String title;
    private boolean isUseWebViewTitle=true;

    protected View mTitleBarBack;
    protected View mTitleBarClose;
    private TextView mTitleView;

    private ShareBean shareHandleBean;
    public static void launch(String url, String title, Context context) {

        Intent intent=new Intent(context,WebActivity.class);
        intent.putExtra(EXTRA_URL, url);
        if (!TextUtils.isEmpty(title)) {
            intent.putExtra(EXTRA_WEB_TITLE, title);
        }
        context.startActivity(intent);
    }
    public static void launch(Context context,String url, String title, ShareBean shareBean) {

        Intent intent=new Intent(context,WebActivity.class);
        intent.putExtra(EXTRA_URL, url);

        if (!TextUtils.isEmpty(title)) {
            intent.putExtra(EXTRA_WEB_TITLE, title);
        }
        intent.putExtra(EXTRA_SHARE_DATA, shareBean);
        context.startActivity(intent);
    }
    public static void launch(String url, String title, int cacheMode, Context context) {
        Intent intent=new Intent(context,WebActivity.class);
        intent.putExtra(EXTRA_URL, url);
        if (!TextUtils.isEmpty(title)) {
            intent.putExtra(EXTRA_WEB_TITLE, title);
        }
        intent.putExtra(EXTRA_CACHE_MODE,cacheMode);
        context.startActivity(intent);

    }

    @Override
    protected int getLayoutView() {
        return R.layout.activity_webview;
    }

    @Override
    protected void initView(View view) {
        EventUtils.getDefault().register(this);
        refreshCookie(this);
        if (mWebView != null) {
            mWebView.destroy();
        }
        mRootView = ((FrameLayout) findViewById(R.id.root));
        //mWebView = (CommonWebView) view.findViewById(R.id.webview);
        // because CommonWebView will be used in multiple window mode, we use application context to avoid context leak
        mWebView = new CommonWebView(this);
//        mWebView.setWebChromeClient(new MyWebChromeClient());
        mWebView.setId(R.id.webview);
        mRootView.addView(mWebView, 0, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT));

        mIsWebViewAvailable = true;

        mErrorView = (WebErrorView) mRootView.findViewById(R.id.error);
        mWebView.setErrorView(mErrorView);
        mErrorView.setErrorViewClickListener(this);

        mProgressBar = (AutoStepProgressBar) mRootView.findViewById(R.id.progress_bar);
        mWebView.setLoading(mProgressBar);

//        WVJBWebViewClient.WVJBWebViewClientBuilder builder=new WVJBWebViewClient.WVJBWebViewClientBuilder(mWebView, new MyWebViewClient());
//        registerWVJBhandler(builder);
//        WVJBWebViewClient wvjbWebViewClient=builder.build();
//        callHandler(wvjbWebViewClient);
        mWebView.setCustomWebViewClient(new MyWebViewClient());

        settingWebView(mWebView);

        Intent arguments = getIntent();
        if (arguments != null) {
            mOriginUrl=arguments.getStringExtra(EXTRA_URL);
            title=arguments.getStringExtra(EXTRA_WEB_TITLE);
            if(arguments.getIntExtra(EXTRA_CACHE_MODE,-1)!=-1){
                mWebView.getSettings().setCacheMode(arguments.getIntExtra(EXTRA_CACHE_MODE,-1));
            }
            shareHandleBean=arguments.getParcelableExtra(EXTRA_SHARE_DATA);

        }
        initTitleBar();
        if (mOriginUrl != null) {
            mWebView.loadUrl(mOriginUrl);
        }

    }

    @Override
    protected void initData() {

    }


    protected void settingWebView(CommonWebView webView) {

    }
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        if (resultCode == Activity.RESULT_OK) {
//            switch (requestCode) {
//                case LoginWVJBHandler.REQUEST_CODE_LOGIN:
//                    refreshCookie(getContext());
//                    mWebView.refresh();
//                    break;
//            }
//        }
    }
    public void refreshCookie(Context context) {

    }



    /**
     * Called when the fragment is no longer resumed. Pauses the WebView.
     */
    @Override
    public void onPause() {
        super.onPause();
        mWebView.safeOnPause();
    }

    /**
     * Called when the fragment is visible to the user and actively running. Resumes the WebView.
     */
    @Override
    public void onResume() {
        mWebView.safeOnResume();
        super.onResume();
    }


    /**
     * Called when the fragment is no longer in use. Destroys the internal state of the WebView.
     */
    @Override
    public void onDestroy() {
        mIsWebViewAvailable = false;
        if (mDestroyWebView) {
            if (mWebView != null) {
                mWebView.destroy();
                mWebView = null;
            }
        } else {
            setWebView(null);
        }
        EventUtils.getDefault().unregister(this);
        super.onDestroy();
    }


    public void forceSetWebView(CommonWebView webView) {
        mWebView = webView;
    }

    /**
     * Gets the WebView.
     */
    public WebView getWebView() {
        return mIsWebViewAvailable ? mWebView : null;
    }

    public void setWebView(CommonWebView webView) {
        if (mWebView == webView) {
            return;
        }
        FrameLayout.LayoutParams params = null;
        if (mWebView != null) {
            mWebView.onPause();
            params = (FrameLayout.LayoutParams) mWebView.getLayoutParams();
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mWebView.setErrorView(null);
            mWebView.setLoading(null);
        }
        mWebView = webView;
        if (mWebView != null) {
            mWebView.onResume();
            if (params == null) {
                params = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                        ViewGroup.LayoutParams.MATCH_PARENT);
            }
            ViewParent parent = mWebView.getParent();
            if (parent != null) {
                ((ViewGroup) parent).removeView(mWebView);
            }
            mRootView.addView(mWebView, 0, params);
            mWebView.setErrorView(mErrorView);
            mWebView.setLoading(mProgressBar);
        }
    }

    public void setDestroyWebView(boolean destroyWebView) {
        mDestroyWebView = destroyWebView;
    }

    @Override
    public void onRefreshClicked() {
        mWebView.refresh();
    }




    private class MyWebViewClient extends DefaultWebViewClient {

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            onWebPageFinished(view, url);
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url.startsWith(HTTP) || url.startsWith(HTTPS)) {
                view.loadUrl(url);
            } else if (url.startsWith(TELEPHONY)) {
                try {
                    Intent intent = new Intent(Intent.ACTION_DIAL,
                            Uri.parse(url));
                    startActivity(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            } else if (url.startsWith(NATIVE)) {
//                Uri uri = Uri.parse(url);
//                Bundle bundle = new Bundle();
//                if (uri.isHierarchical()) {
//                    Set<String> names = uri.getQueryParameterNames();
//                    for (String name : names) {
//                        bundle.putString(name, uri.getQueryParameter(name));
//                    }
//                }
//                bundle.putBoolean(CUSTOM, true);
//                String host = uri.getHost();
//                String query = uri.getQuery();
//                uri = UriManager.getPageUri(host);
//                UriBuilder builder = UriBuilder.newInstance(uri);
//                builder.appendQueryString(query);
//                uri = builder.build();
//
//                LauncherActivity.openURL(uri, bundle, getActivity().getIntent(), getActivity());
            }
            return true;
        }
    }
    public void setUseWebViewTitle(boolean useWebViewTitle){
        isUseWebViewTitle=useWebViewTitle;
    }
    protected void onWebPageFinished(WebView view, String url) {
        updateLeftBar();
        if (TextUtils.isEmpty(title) && isUseWebViewTitle) {
            ((TextView)findViewById(R.id.bar_tv_title)).setText(view.getTitle());

        }
    }
    private void initTitleBar() {
        mTitleView= (TextView) findViewById(R.id.bar_tv_title);
        mTitleBarBack=findViewById(R.id.bar_img_back);
        mTitleBarClose=findViewById(R.id.bar_tv_close);
        mTitleBarClose.setVisibility(View.INVISIBLE);
        ImageView shareIv = (ImageView) findViewById(R.id.bar_img_more);
        shareIv.setVisibility(View.INVISIBLE);
        if(shareHandleBean!=null) {
            shareIv.setVisibility(View.VISIBLE);
            shareIv.setImageResource(R.mipmap.share);
        }
        if(!TextUtils.isEmpty(title)){
            mTitleView.setText(title);
        }
        View.OnClickListener clickListener=new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (v == mTitleBarBack) {
                    if (mWebView.canGoBack()) {
                        mWebView.goBack();
                    } else {
                        finish();
                    }
                }
                else if (v == mTitleBarClose) {
                    finish();
                }else if(v==shareIv){
                    requeesSharePermission();
                }
            }
        };
        shareIv.setOnClickListener(clickListener);
        mTitleBarBack.setOnClickListener(clickListener);
        mTitleBarClose.setOnClickListener(clickListener);
    }

    private void updateLeftBar() {
        if (mWebView.canGoBack()) {
            mTitleBarClose.setVisibility(View.VISIBLE);
        } else {
            mTitleBarClose.setVisibility(View.INVISIBLE);
        }
    }
    @Override
    public void update(Object obj) {
        if(obj instanceof ShareBean){
            shareHandleBean= (ShareBean) obj;
            requeesSharePermission();
        }
    }

    private void requeesSharePermission(){
        String[] mPermissionList = new String[]{
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.ACCESS_WIFI_STATE
//                    Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.CALL_PHONE,
//                    Manifest.permission.READ_LOGS,
//                    Manifest.permission.READ_PHONE_STATE,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.SET_DEBUG_APP,
//                    Manifest.permission.SYSTEM_ALERT_WINDOW,
//                    Manifest.permission.GET_ACCOUNTS,
//                    Manifest.permission.WRITE_APN_SETTINGS
        };
        PermissionHelper.requestMultiPermissions(this,PERMISSION_SHARE,null,permissionResult,mPermissionList);
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        PermissionHelper.requestPermissionsResult(requestCode,permissions,grantResults,permissionResult);
    }
    PermissionHelper.PermissionResult permissionResult=new PermissionHelper.PermissionResult() {
        @Override
        public void onPermissionGranted(int requestCode) {
            switch (requestCode){
                case PERMISSION_SHARE:
                    break;
            }
        }

        @Override
        public void onPermissionDenied(int requestCode, String... noPermissions) {
            switch (requestCode){
                case PERMISSION_SHARE:
                    PermissionHelper.permissionDined(WebActivity.this,"您拒绝了《存储》权限，无法使用分享功能，若想继续分享，请手动开启","您拒绝了《存储》权限，无法使用分享功能.");
                    break;
//                case PERMISSION_SHARE:
//                    String des="";
//                    for(String permission:noPermissions){
//                        if(permission.equals(Manifest.permission.CALL_PHONE)){
//                            des+="<拨打电话>";
//                        }
//                        if(permission.equals(Manifest.permission.CAMERA)){
//                            des+="<相机>";
//                        }
//                    }
//                    PermissionHelper.permissionDined(WebActivity.this,"您拒绝了"+des+"权限，无法正常使用此功能模块，若想继续使用，请手动开启","您拒绝了"+des+"权限，无法正常使用此功能");
//                    break;
            }
        }
    };

}
